const api = require('../fetch/api')
const app = getApp()
Component({
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2,
          num: ''
        })
      }
      this.clear()
      app.authTo(()=>{
        this.message()
      })
    },
  },
  lifetimes: {
    attached() {}
  },
  data: {
    arr: [],
    loading: false,
    finished: false,
    page: 1,
  },
  methods: {
    detail(e) {
      const { id } = app.dataSet(e)
      wx.navigateTo({
        url: '/pages/messageDetail/index?id=' + id,
      })
    },
    clear() {
      this.setData({
        arr: [],
        loading: false,
        finished: false,
        page: 1,
      })
    },
    async message() {
      if (!this.data.loading) {
        this.setData({
          loading: true
        })
        let res = await api.message({
          page: this.data.page,
        })
        let finished = false
        res.data.length == 0 && (finished = true)
        this.setData({
          arr: [...this.data.arr, ...res.data],
          finished,
          loading: false
        })
      }
    },
    onReachBottom() {
      let {
        page,
        finished
      } = this.data
      if (!finished) {
        this.setData({
          page: page + 1
        })
        this.message()
      }
    },
  }
})